package com.clever.security.handler;

import com.clever.commons.result.BaseResult;
import com.clever.security.dto.UserDto;
import com.clever.security.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ChenWang
 * @date 2020/12/14 13:59
 * @since JDK 1.8
 */
@Component
public class LoginSuccessfulHandler implements AuthenticationSuccessHandler {
    @Resource
    ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取认证对象 例如：UserDto
        UserDto userDto =(UserDto) authentication.getPrincipal();
        // 生成jwt

        // 原生的把数据转成json并且发送回前端
        ResponseUtil.responseTpJson(response,objectMapper, BaseResult.success(userDto));
    }
}
